package game;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.geom.GeneralPath;

public class LoveHeart extends JFrame {
    // 将message声明为final（不可变）
    private final String message;

    public LoveHeart(String message) {
        this.message = message;
        initUI();
    }

    private void initUI() {
        setTitle("爱心动画");
        setSize(400, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null); // 窗口居中

        JPanel panel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                // 开启抗锯齿，使图形更平滑
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                // 保存当前图形上下文状态（替换save()）
                Graphics2D g2dCopy = (Graphics2D) g2d.create();

                // 绘制爱心
                drawHeart(g2dCopy, getWidth() / 2, getHeight() / 2, 100);

                // 绘制文字
                g2dCopy.setColor(Color.RED);
                g2dCopy.setFont(new Font("Arial", Font.BOLD, 20));
                FontMetrics fm = g2dCopy.getFontMetrics();
                int textX = getWidth() / 2 - fm.stringWidth(message) / 2;
                int textY = getHeight() / 2 + 10;
                g2dCopy.drawString(message, textX, textY);

                // 恢复状态（替换restore()，销毁副本）
                g2dCopy.dispose();
            }

            private void drawHeart(Graphics2D g, int x, int y, int size) {
                GeneralPath heart = new GeneralPath();
                // 绘制爱心路径（基于数学公式）
                heart.moveTo(x, y - size / 4);
                heart.curveTo(
                        x + size / 2, y - size,
                        x + size, y + size / 4,
                        x, y + size / 2
                );
                heart.curveTo(
                        x - size, y + size / 4,
                        x - size / 2, y - size,
                        x, y - size / 4
                );
                g.setColor(Color.PINK);
                g.fill(heart); // 填充爱心
                g.setColor(Color.RED);
                g.setStroke(new BasicStroke(2));
                g.draw(heart); // 绘制爱心边框
            }
        };

        add(panel);

        // 用Lambda简化ActionListener
        Timer timer = new Timer(50, (ActionEvent e) -> {
            panel.repaint(); // 定时重绘，实现动画效果
        });
        timer.start();
    }

    public static void main(String[] args) {
        // 用Lambda简化Swing线程调度（Runnable）
        SwingUtilities.invokeLater(() -> {
            new LoveHeart("I Love You").setVisible(true);
        });
    }
}